package com.pipayshop.service.impl;

import com.pipayshop.domain.StoreCommodityEvaluate;
import com.pipayshop.domain.StoreOrderInfo;
import com.pipayshop.domain.dto.StoreCommodityEvaluateDTO;
import com.pipayshop.domain.vo.PageDataVO;
import com.pipayshop.domain.vo.StoreCommodityEvaluateVO;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.PhysicalStoreCommodityEvaluateMapper;
import com.pipayshop.mapper.PhysicalStoreCommodityInfoMapper;
import com.pipayshop.mapper.PhysicalStoreOrderInfoMapper;
import com.pipayshop.service.PhysicalStoreCommodityEvaluateService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pipayshop.utils.Constants;
import com.pipayshop.utils.StringUtil;
import com.pipayshop.utils.ValidationUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxb
 * @since 2023-07-27
 */
@Service
public class PhysicalStoreCommodityEvaluateServiceImpl extends ServiceImpl<PhysicalStoreCommodityEvaluateMapper, StoreCommodityEvaluate> implements PhysicalStoreCommodityEvaluateService {

    @Resource
    private PhysicalStoreCommodityEvaluateMapper shopCommodityEvaluateMapper;

    @Resource
    PhysicalStoreCommodityInfoMapper shopCommodityInfoMapper;

    @Resource
    PhysicalStoreOrderInfoMapper shopOrderInfoMapper;
    /**
     * 实体店-商品-评论列表
     */
    @Override
    public PageDataVO commodityEvaluateList(String commodityId, Integer pageNum, Integer pageSize) {
        List<StoreCommodityEvaluateVO> result = shopCommodityEvaluateMapper.commodityEvaluateList(commodityId, (pageNum-1)*pageSize, pageSize);
        Long count = shopCommodityEvaluateMapper.selectCount(new QueryWrapper<StoreCommodityEvaluate>()
                .eq("commodity_id", commodityId)
                .eq("status", 0));
        return new PageDataVO(count.intValue(), result);
    }

    /**
     * 实体店-商品-添加评论
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = Constants.PHYSICAL_STORE_ORDER_LIST_KEY, allEntries = true)
    public Boolean addEvaluate(StoreCommodityEvaluateDTO dto) {
        // 校验传入DTO的字段
        ValidationUtil.validateNotNull(dto, "review_content_required。");
        ValidationUtil.validateString(dto.getCommodityId(), "commodity_id_required。");
        ValidationUtil.validateString(dto.getUserId(), "user_id_required。");
        ValidationUtil.validateString(dto.getEvaluate(), "review_content_required。");
        ValidationUtil.validateScore(dto.getScore(),1,5,"comment_score_out_of_range");
        ValidationUtil.validateString(dto.getOrderId(), "order_id_required。");
        // 查询当前实体店商品所在的网店id
        String shopId = shopCommodityInfoMapper.selectShopIdByOrderId(dto.getOrderId());

        // 创建评价对象并复制属性
        StoreCommodityEvaluate evaluate = new StoreCommodityEvaluate();
        BeanUtils.copyProperties(dto, evaluate);
        evaluate.setItemId(shopId);  // 设置店铺ID
        evaluate.setEvaluateId(StringUtil.generateShortId());  // 生成评价ID
        evaluate.setStatus(false);  // 设置初始状态为未审核

        // 更新订单状态为已评价（假设4为已评价）
        int update = shopOrderInfoMapper.update(null, new UpdateWrapper<StoreOrderInfo>()
                .eq("order_id", dto.getOrderId())
                .set("order_status", 4));
        if (update < 1) {
            throw new BusinessException("order_update_failed");
        }

        // 插入评价记录
        return shopCommodityEvaluateMapper.insert(evaluate) > 0;
    }


    /**
     * 实体店-商品-删除评论
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = Constants.PHYSICAL_STORE_ORDER_LIST_KEY, allEntries = true)
    public Boolean deleteEvaluate(String evaluateId, String userId) {
        return shopCommodityEvaluateMapper.update(null, new LambdaUpdateWrapper<StoreCommodityEvaluate>()
                .eq(StoreCommodityEvaluate::getEvaluateId, evaluateId)
                .eq(StoreCommodityEvaluate::getUserId, userId)
                .set(StoreCommodityEvaluate::getStatus, true)
        ) > 0;
    }
}
